package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户权益管理控制器
 * 统一处理用户权益的获取和更新
 */
@RestController
@RequestMapping("/user")
public class UserBenefitsController {
    
    @Resource
    private UserService userService;
    
    /**
     * 用户权益管理接口
     * 支持获取和更新用户权益信息
     * 
     * @param userId 用户ID或账号
     * @param request 更新请求体（可选）
     * @return 用户权益信息
     */
    @RequestMapping(value = "/{userId}/benefits", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<Map<String, Object>> userBenefits(@PathVariable String userId, 
                                                           @RequestBody(required = false) Map<String, Object> request) {
        try {
            // 查找用户（支持ID和账号查询）
            User user = findUser(userId);
            
            if (user == null) {
                return ResponseEntity.ok(Map.of(
                    "success", false,
                    "message", "用户不存在"
                ));
            }
            
            // 如果是POST请求，执行更新操作
            if (request != null && !request.isEmpty()) {
                updateUserBenefits(user, request);
                userService.updateById(user);
            }
            
            // 构建返回数据
            Map<String, Object> benefits = buildBenefitsData(user);
            
            return ResponseEntity.ok(Map.of(
                "success", true,
                "message", request != null ? "用户权益更新成功" : "获取用户权益成功",
                "data", benefits
            ));
            
        } catch (Exception e) {
            return ResponseEntity.ok(Map.of(
                "success", false,
                "message", "操作失败: " + e.getMessage()
            ));
        }
    }
    
    /**
     * 查找用户（支持ID和账号查询）
     */
    private User findUser(String userId) {
        try {
            // 先尝试按ID查询
            User user = userService.getById(Long.parseLong(userId));
            if (user != null) {
                return user;
            }
        } catch (NumberFormatException e) {
            // 如果解析失败，说明不是数字ID，按账号查询
        }
        
        // 按账号查询
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getAccount, userId);
        return userService.getOne(queryWrapper);
    }
    
    /**
     * 更新用户权益
     */
    private void updateUserBenefits(User user, Map<String, Object> request) {
        if (request.containsKey("totalTokens")) {
            user.setTotalTokens((Integer) request.get("totalTokens"));
        }
        if (request.containsKey("totalValidityDays")) {
            user.setTotalValidityDays((Integer) request.get("totalValidityDays"));
        }
        if (request.containsKey("expiresAt")) {
            String expiresAtStr = (String) request.get("expiresAt");
            if (expiresAtStr != null && !expiresAtStr.isEmpty()) {
                user.setExpiresAt(LocalDateTime.parse(expiresAtStr));
            }
        }
        user.setLastBenefitUpdate(LocalDateTime.now());
    }
    
    /**
     * 构建权益数据
     */
    private Map<String, Object> buildBenefitsData(User user) {
        Map<String, Object> benefits = new HashMap<>();
        benefits.put("id", user.getId());
        benefits.put("account", user.getAccount());
        benefits.put("name", user.getName());
        benefits.put("totalTokens", user.getTotalTokens() != null ? user.getTotalTokens() : 0);
        benefits.put("totalValidityDays", user.getTotalValidityDays() != null ? user.getTotalValidityDays() : 0);
        benefits.put("expiresAt", user.getExpiresAt());
        benefits.put("lastBenefitUpdate", user.getLastBenefitUpdate());
        return benefits;
    }
}
